package com.mall.service.authority.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mall.autoconfig.interceptor.BaseContext;
import com.mall.commons.common.CommonPage;
import com.mall.commons.common.CommonResult;
import com.mall.commons.exception.CustomException;
import com.mall.commons.utils.JwtUtils;
import com.mall.model.domain.*;
import com.mall.model.dto.InfoDto;
import com.mall.service.authority.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;


import java.util.*;
import java.util.regex.Pattern;


/**
 * @ClassName AdminService
 * @Description 用户接口逻辑层
 * @Author dcq
 * @Date 2023/3/11 16:22
 * @Version 1.0
 */
@Service
public class AdminService {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private AdminAndRoleMapper adminAndRoleMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RoleMenuMapper roleAndMenuMapper;
    @Autowired
    private UmsMenuMapper menuMapper;
    @Autowired
    private static AdminMapper umsAdminMapper;
    @Autowired(required = false)
    UmsAdminRoleRelationService umsAdminRoleRelationService;
    @Autowired(required = false)
    UmsRoleService umsRoleService;


    //登录

    public Map loginSei(String username,String password) {

        LambdaQueryWrapper<UmsAdmin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(username != null, UmsAdmin::getUsername, username);
        UmsAdmin umsAdmin = adminMapper.selectOne(queryWrapper);
        if (umsAdmin == null) {
            throw new CustomException("用户不存在");
        }
        if (!umsAdmin.getPassword().equals(password)) {
            throw new CustomException("密码错误");
            }
        Map tokenMap = new HashMap();
        tokenMap.put("id", umsAdmin.getId());
        String token = JwtUtils.getToken(tokenMap);
        HashMap result = new HashMap<>();
        result.put("token", token);
        result.put("tokenHead","Bearer ");
        return result;
    }
    //当前用户登录信息

    public InfoDto infoSei( String name) {
        //获取登录用户基本信息
//        LambdaQueryWrapper<UmsAdmin> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(name != null, UmsAdmin::getUsername, name);
//        UmsAdmin umsAdmin = adminMapper.selectOne(queryWrapper);
        String currentId = BaseContext.getCurrentId();
        UmsAdmin umsAdmin = adminMapper.selectById(currentId);

        //根据id找出用户对应的角色表
        LambdaQueryWrapper<UmsAdminRoleRelation> queryWrapperUrr=new LambdaQueryWrapper<>();
        queryWrapperUrr.eq(UmsAdminRoleRelation::getAdminId,currentId);
        UmsAdminRoleRelation umsAdminRoleRelation = adminAndRoleMapper.selectOne(queryWrapperUrr);
        //角色表对应的id
        Long roleId = umsAdminRoleRelation.getRoleId();
        UmsRole umsRole = roleMapper.selectById(roleId);
        LambdaQueryWrapper<UmsRoleMenuRelation>queryWrapperUrmr=new LambdaQueryWrapper<>();
        queryWrapperUrmr.eq(umsRole!=null,UmsRoleMenuRelation::getRoleId,umsRole.getId());
        //根据角色id   找出相对应的权限
        List<UmsRoleMenuRelation> umsRoleMenuRelations = roleAndMenuMapper.selectList(queryWrapperUrmr);
        List<Long> menuId = CollUtil.getFieldValues(umsRoleMenuRelations, "menuId", Long.class);
        LambdaQueryWrapper<UmsMenu>queryWrapperUm=new LambdaQueryWrapper<>();
        queryWrapperUm.in(UmsMenu::getId,menuId);
        List<UmsMenu> umsMenus = menuMapper.selectList(queryWrapperUm);
        InfoDto infoDto = new InfoDto();
         infoDto.setMenus(umsMenus);
         infoDto.setIcon(umsAdmin.getIcon());
         infoDto.setUsername(umsAdmin.getUsername());
         String[] arr=new String[]{umsRole.getName()};
         infoDto.setRoles(arr);

        return infoDto;
    }
    //删除用户信息
    public void deleteSei(Integer id) {
      adminMapper.deleteById(id);
    }

    public CommonPage listSei(Integer pageNum, Integer pageSize, String keyword) {
        Page<UmsAdmin> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<UmsAdmin>queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.like(null!=keyword,UmsAdmin::getUsername,keyword);
       adminMapper.selectPage(page, queryWrapper);
        CommonPage page1 = CommonPage.getPage(page);
        return  page1;
    }

    public UmsAdmin getId(String id) {
        UmsAdmin admin = adminMapper.selectById(id);
        return admin;
    }


    public String register(UmsAdmin umsAdmin) {
        LambdaQueryWrapper<UmsAdmin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UmsAdmin::getUsername,umsAdmin.getUsername());
        UmsAdmin one = adminMapper.selectOne(queryWrapper);
        if (null!=one){
            return "用户已经存在";
        }

        // 用户名为空,结束,返回错误信息
        if (StrUtil.isEmpty(umsAdmin.getUsername())) {
            return "用户名不能为空";
        }

        // 密码为空,结束,返回错误信息
        if (StrUtil.isEmpty(umsAdmin.getPassword())) {
            return "密码不能为空";
        }
        // 校验邮箱格式,如果格式错误,返回错误信息
        if (StrUtil.isNotEmpty(umsAdmin.getEmail())) {
            String check = "^(\\w+([-.][A-Za-z0-9]+)*){3,18}@\\w+([-.][A-Za-z0-9]+)*\\.\\w+([-.][A-Za-z0-9]+)*$";
            if (!Pattern.matches(check, umsAdmin.getEmail())) {
                return "邮箱格式不正确!";
            }
        }
        //走到这一步, 则可以进行注册
        // 保存数据
        umsAdmin.setPassword(umsAdmin.getPassword());
        adminMapper.insert(umsAdmin);
        // 查询最新保存的数据
       // UmsAdmin adminNew = umsAdminService.findByOne(umsAdmin.getUsername(),umsAdmin.getPassword());
        return null;
    }

     static void save(UmsAdmin umsAdmin) {
        umsAdminMapper.insert(umsAdmin);
    }

    private  UmsAdmin findByOne(String username, String password) {
        LambdaQueryWrapper<UmsAdmin> qw = new LambdaQueryWrapper<>();
        qw.eq(UmsAdmin::getUsername,username).eq(UmsAdmin::getPassword, SecureUtil.md5(password));

        return umsAdminMapper.selectOne(qw);
    }


    public void updateRoleById(Long adminId, List<Long> roleIds) {
        // 根据 adminId 查询 当前用户的 roleIds
        LambdaQueryWrapper<UmsAdminRoleRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UmsAdminRoleRelation::getAdminId,adminId);
        int delete = adminAndRoleMapper.delete(queryWrapper);
        LambdaQueryWrapper<UmsAdminRoleRelation> wrapper = new LambdaQueryWrapper<>();
        for (Long roleId : roleIds) {
            UmsAdminRoleRelation umsAdminRoleRelation = new UmsAdminRoleRelation();
            umsAdminRoleRelation.setRoleId(roleId);
            umsAdminRoleRelation.setAdminId(adminId);
            adminAndRoleMapper.insert(umsAdminRoleRelation);
        }
    }

    public String update(Long id,UmsAdmin umsAdmin) {
        // 用户名为空,结束,返回错误信息
        if (StrUtil.isEmpty(umsAdmin.getUsername())) {
            return "用户名不能为空!";
        }
        // 密码为空,结束,返回错误信息
        if (StrUtil.isEmpty(umsAdmin.getPassword())) {
            return "密码不能为空!";
        }
        // 校验邮箱格式,如果格式错误,返回错误信息
        if (StrUtil.isNotEmpty(umsAdmin.getEmail())) {
            String check = "^(\\w+([-.][A-Za-z0-9]+)*){3,18}@\\w+([-.][A-Za-z0-9]+)*\\.\\w+([-.][A-Za-z0-9]+)*$";
            if (!Pattern.matches(check,umsAdmin.getEmail())) {
                return "邮箱格式不正确!";
            }
        }
        LambdaQueryWrapper<UmsAdmin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UmsAdmin::getId,id);
        adminMapper.update(umsAdmin,queryWrapper);

        return null;
    }

    public void updateStatus(Long id, Integer status) {
        UmsAdmin umsAdmin = umsAdminMapper.selectById(id);
        umsAdmin.setStatus(status);
        LambdaQueryWrapper<UmsAdmin> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UmsAdmin::getId,id);
        umsAdminMapper.update(umsAdmin, wrapper);
    }

    public List<UmsRole> getRolesInfo(Long adminId) {
        LambdaQueryWrapper<UmsAdminRoleRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UmsAdminRoleRelation::getAdminId,adminId);
        List<UmsAdminRoleRelation> list = adminAndRoleMapper.selectList(queryWrapper);
        if (CollUtil.isEmpty(list)) {
            return new ArrayList<>();
        }
        List<Long> roleIds = CollUtil.getFieldValues(list, "roleId", Long.class);
        LambdaQueryWrapper<UmsRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(UmsRole::getId,roleIds);
        List<UmsRole> roles = roleMapper.selectList(wrapper);
        return roles;
    }
}
